package com.inossem.allotin.utils.requestUtils;

import com.inossem.allotin.utils.ToastUtils;
import com.inossem.wms.vo.BaseObject;
import com.orhanobut.logger.Logger;

import java.lang.reflect.UndeclaredThrowableException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 自定义Callback
 *
 * @author 郭晓龙
 * @time on 2019/06/17
 * @email xiaolong.guo@inossem.com
 */
public abstract class InossemNewsCallback<T extends BaseObject> implements Callback<T> {

    private final static int SUCCESS = 1;
    private final static int LOGIN_FAIL = 1003;

    //请求成功
    public abstract void success(Response<T> response);

    //请求失败(业务逻辑错误)
    public void failure(Response<T> response) {
        ToastUtils.showToast(response.body().getReturnMsg());
    }

    //请求失败(HTTP错误)
    public void httpError(Throwable t) {
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            if (null != response.body() && null != response.body().getReturnCode()) {
                switch (response.body().getReturnCode()) {
                    case SUCCESS://成功
                        success(response);
                        break;
                    case LOGIN_FAIL://登录过期
//                        InossemApplication.getContext().startHomeActivity();
                        break;
                    default://提交失败
                        failure(response);
                        break;
                }
            } else {
                ToastUtils.showToast("返回数据错误");
            }
        } else {
            ToastUtils.showToast("请求错误" + "\t" + response.raw().toString());
        }
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        httpError(t);
        ToastUtils.showToast(getErrorMessage(t));
        try {
            Logger.e(getErrorMessage(t));
        } catch (Exception ignored) {
        }
    }

    private String getErrorMessage(Throwable e) {
        String msg = null;
        if (e instanceof UndeclaredThrowableException) {
            Throwable targetEx = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            if (targetEx != null) {
                msg = targetEx.getMessage();
            }
        } else {
            msg = e.getMessage();
        }
        return msg;
    }
}
